﻿using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using static System.Net.Mime.MediaTypeNames;

namespace Gdmec.Util
{
    public class WebUtil
    {

        /// <summary>
        /// 读取服务器任何文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="onCall"></param>
        /// <returns></returns>
        public static IEnumerator GetBytes(string url, System.Action<bool, byte[]> onCall)
        {
            using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
            {
                yield return webRequest.SendWebRequest();
                if (webRequest.isNetworkError || webRequest.isHttpError)
                {
                    if (onCall != null) onCall(false, null);
                }
                else
                {
                    DownloadHandler fileHandler = webRequest.downloadHandler;
                    if (onCall != null) onCall(true, fileHandler.data);
                }
            }
        }

    
        /// <summary>
        /// 读取服务器.txt文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="onCall"></param>
        /// <returns></returns>
        public static IEnumerator GetText(string url, System.Action<bool, string> onCall)
        {
            yield return GetBytes(url, (bool isOk, byte[] bytes) => 
            {
                if (isOk)
                {
                    if (onCall != null) onCall(true, System.Text.Encoding.UTF8.GetString(bytes));
                }
                else 
                {
                    if (onCall != null) onCall(false, string.Empty);
                }
            });
        }
    }
}
